package com.fram.service.api.v1.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.fram.bean.api.order.request.CommentScoreRequest;
import com.fram.bean.api.order.request.GoodsCreateOrderRequest;
import com.fram.bean.api.order.request.OrderApplyRefundRequest;
import com.fram.bean.api.order.request.OrderMyCommentRequest;
import com.fram.bean.api.order.request.OrderRevokeRefundRequest;
import com.fram.bean.api.order.request.OrderSearchRequest;
import com.fram.bean.api.order.request.ShopCartCreateOrderRequest;
import com.fram.bean.api.order.response.OrderCreateResponse;
import com.fram.bean.api.order.response.OrderDetailResponse;
import com.fram.bean.api.order.response.OrderMyCommentResponse;
import com.fram.bean.api.order.response.OrderSearchResponse;
import com.fram.bean.api.order.response.OrderStatusNumberResponse;
import com.fram.bean.api.project.response.ProjectGoodsDetailResponse;
import com.fram.bean.api.shopcart.response.ShopCartSearchResponse;
import com.fram.bean.sys.PageBean;
import com.fram.bean.sys.pay.PayResultMsg;
import com.fram.common.async.AsyncMethod;
import com.fram.common.canstant.ErrCode;
import com.fram.common.canstant.PublicConstant;
import com.fram.common.enums.OrderStatusEnum;
import com.fram.common.enums.PayCodeEnum;
import com.fram.common.exception.ProAffairException;
import com.fram.common.exception.ProException;
import com.fram.common.exception.ProRunTimeException;
import com.fram.common.exception.ProValiDataException;
import com.fram.common.util.BeanMapper;
import com.fram.common.util.PublicMethod;
import com.fram.common.util.alipay.AlipayUtils;
import com.fram.common.util.base.BaseService;
import com.fram.common.util.date.DateUtils;
import com.fram.common.util.qiniu.QiniuUtils;
import com.fram.common.util.tencent.TencentUtils;
import com.fram.common.util.wxpay.WXPayUtils;
import com.fram.entity.MessageData;
import com.fram.entity.OrderAddress;
import com.fram.entity.OrderComment;
import com.fram.entity.OrderDetail;
import com.fram.entity.OrderGoods;
import com.fram.entity.OrderMain;
import com.fram.entity.OrderRefund;
import com.fram.entity.OrderScore;
import com.fram.entity.ProjectGoods;
import com.fram.entity.ProjectGoodsPrice;
import com.fram.entity.SysPayment;
import com.fram.entity.UserReceivingAddress;
import com.fram.entity.UserTransactionFlow;
import com.fram.mapper.MessageDataMapper;
import com.fram.mapper.OrderAddressMapper;
import com.fram.mapper.OrderCommentMapper;
import com.fram.mapper.OrderDetailMapper;
import com.fram.mapper.OrderGoodsMapper;
import com.fram.mapper.OrderMainMapper;
import com.fram.mapper.OrderRefundMapper;
import com.fram.mapper.OrderScoreMapper;
import com.fram.mapper.OrderShoppingcartMapper;
import com.fram.mapper.ProjectGoodsMapper;
import com.fram.mapper.ProjectGoodsPriceMapper;
import com.fram.mapper.SysPaymentMapper;
import com.fram.mapper.UserLoginMapper;
import com.fram.mapper.UserReceivingAddressMapper;
import com.fram.mapper.UserTransactionFlowMapper;
import com.fram.service.api.v1.OrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service("orderService")
public class OrderServiceImpl extends BaseService implements OrderService {

	private static Logger LOG = LoggerFactory.getLogger(OrderServiceImpl.class);

	@Autowired
	private OrderShoppingcartMapper orderShoppingcartMapper;
	@Autowired
	private UserReceivingAddressMapper userReceivingAddressMapper;
	@Autowired
	private OrderMainMapper orderMainMapper;
	@Autowired
	private OrderAddressMapper orderAddressMapper;
	@Autowired
	private OrderDetailMapper orderDetailMapper;
	@Autowired
	private OrderGoodsMapper orderGoodsMapper;
	@Autowired
	private ProjectGoodsMapper projectGoodsMapper;
	@Autowired
	private SysPaymentMapper paymentMapper;
	@Autowired
	private OrderRefundMapper orderRefundMapper;
	@Autowired
	private UserTransactionFlowMapper userTransactionFlowMapper;
	@Autowired
	private OrderCommentMapper orderCommentMapper;
	@Autowired
	private OrderScoreMapper orderScoreMapper;
	@Autowired
	private UserLoginMapper userLoginMapper;
	@Autowired
	private MessageDataMapper messageDataMapper;
	@Autowired
	private ProjectGoodsPriceMapper projectGoodsPriceMapper;
	@Autowired
	private AsyncMethod asyncMethod;

	@Autowired
	private QiniuUtils qiniuUtils;
	@Autowired
	private TencentUtils tencentUtils;

	@Override
	@Transactional
	public OrderCreateResponse shopCartCreateOrder(ShopCartCreateOrderRequest request) throws ProAffairException {
		synchronized (request.getDistributorId()) {// 相同分销商同一时间只能有一个人下单
			List<ShopCartSearchResponse> cartList = orderShoppingcartMapper.selectForApi(null, null, request.getCartIds());
			if (cartList == null || cartList.size() == 0) {
				throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
			}
			// 判读上下架 剩余量是否能够下单
			/** 商品总金额 **/
			BigDecimal goodsTotalPrice = new BigDecimal("0");
			/** 商品总优惠金额 **/
			BigDecimal goodsTotalVoucherPrice = new BigDecimal("0");
			/** 运费 **/
			BigDecimal logisticsPrice = new BigDecimal("0");
			for (ShopCartSearchResponse cart : cartList) {
				if (request.getDistributorId() != cart.getDistributorId()) {
					throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "分销商与订单创建信息不匹配");
				}
				if (cart.getStatus() != PublicConstant.GOODS_STATUS_1) {
					throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "商品【" + cart.getName() + "】已经下架！无法下单");
				}
				if (cart.getBanlanceNumber() < cart.getNumber()) {
					throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "商品【" + cart.getName() + "】数量不足！无法下单，剩余数量：" + cart.getBanlanceNumber());
				}
				// 运费取最大值
				if (cart.getLogisticsPrice().doubleValue() > logisticsPrice.doubleValue()) {
					logisticsPrice = cart.getLogisticsPrice();
				}
				BigDecimal price = cart.getPrice().multiply(new BigDecimal(cart.getNumber().toString()));
				BigDecimal voucherPrice = cart.getVoucherPrice().multiply(new BigDecimal(cart.getNumber().toString()));
				goodsTotalPrice = goodsTotalPrice.add(price).setScale(2, BigDecimal.ROUND_HALF_UP);
				goodsTotalVoucherPrice = goodsTotalVoucherPrice.add(voucherPrice).setScale(2, BigDecimal.ROUND_HALF_UP);

				// 减掉剩余数量 增加销售量
				ProjectGoodsPrice updateGoods = new ProjectGoodsPrice();
				updateGoods.setId(cart.getResId());
				updateGoods.setBanlanceNumber(cart.getBanlanceNumber() - cart.getNumber());
				if (projectGoodsPriceMapper.updateByPrimaryKeySelective(updateGoods) == 0) {
					throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "更改商品剩余数量出错");
				}
			}
			UserReceivingAddress address = userReceivingAddressMapper.selectByPrimaryKey(request.getAddressId());
			if (address == null) {
				throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
			}
			// 生成主订单
			Date nowDate = new Date();
			OrderMain main = new OrderMain();
			main.setOrderNumber(PublicMethod.getOrderNumber(PublicConstant.ORDER_TYPE_1, null));
			main.setUserId(request.getUserId());
			main.setDistributorId(request.getDistributorId());
			main.setOrderStatus(OrderStatusEnum.MAIN_ORDER_STATUS_1.getStatus());
			main.setCreateTime(nowDate);
			main.setInvalidTime(DateUtils.getAddorSubtractTimes(nowDate, 0, PublicConstant.ORDER_INVALID_TIME, 0, 0, 0, 0));
			main.setActualPrice(goodsTotalPrice.add(logisticsPrice));
			main.setVoucherPrice(goodsTotalVoucherPrice);
			main.setLogisticsPrice(logisticsPrice);
			main.setTotalPrice(main.getActualPrice().add(main.getVoucherPrice()));
			main.setSource(request.getSource());
			main.setRemark(request.getRemark());
			main.setIp(PublicMethod.getIp(PublicMethod.getRequest()));
			if (orderMainMapper.insertSelective(main) == 0 || main.getId() == null) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "主订单," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}
			// 地址
			OrderAddress orderAddress = BeanMapper.map(address, OrderAddress.class);
			orderAddress.setMainOrderId(main.getId());
			orderAddress.setId(null);
			if (orderAddressMapper.insertSelective(orderAddress) == 0) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "记录地址失败," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}
			// 订单详情
			for (ShopCartSearchResponse cart : cartList) {
				OrderDetail detail = new OrderDetail();
				detail.setMainOrderId(main.getId());
				detail.setNumber(cart.getNumber());
				detail.setOriginalProjectId(cart.getResId());
				if (orderDetailMapper.insertSelective(detail) == 0 || detail.getId() == null) {
					throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "详情," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
				}
				// 商品
				OrderGoods orderGoods = BeanMapper.map(cart, OrderGoods.class);
				orderGoods.setOrderDetailId(detail.getId());
				orderGoods.setCategoryId(cart.getParentCategoryId());
				orderGoods.setId(null);
				if (orderGoodsMapper.insertSelective(orderGoods) == 0) {
					throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "商品创建失败," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
				}
			}

			// 删除购物车
			if (orderShoppingcartMapper.deleteByIds(request.getCartIds()) == 0) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "清除购物车失败," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}

			// 返回
			OrderCreateResponse response = new OrderCreateResponse();
			response.setOrderNumber(main.getOrderNumber());
			response.setOrderStatus(main.getOrderStatus());
			response.setCreateTime(main.getCreateTime());
			response.setInvalidTime(main.getInvalidTime());
			response.setActualPrice(main.getActualPrice());
			return response;
		}
	}

	@Override
	@Transactional
	public OrderCreateResponse goodsCreateOrder(GoodsCreateOrderRequest request) throws ProAffairException {
		synchronized (request.getDistributorId()) {// 相同分销商同一时间只能有一个人下单
			ProjectGoodsDetailResponse goods = projectGoodsMapper.detailApi(request.getGoodsId(), request.getUserId());
			if (goods == null) {
				throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
			}
			// 判读上下架 剩余量是否能够下单
			/** 商品总金额 **/
			BigDecimal goodsTotalPrice = new BigDecimal("0");
			/** 商品总优惠金额 **/
			BigDecimal goodsTotalVoucherPrice = new BigDecimal("0");
			/** 运费 **/
			BigDecimal logisticsPrice = goods.getLogisticsPrice();
			if (request.getDistributorId() != goods.getDistributorId()) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "分销商与订单创建信息不匹配");
			}
			if (goods.getStatus() != PublicConstant.GOODS_STATUS_1) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "商品【" + goods.getName() + "】已经下架！无法下单");
			}
			if (goods.getBanlanceNumber() < request.getNumber()) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "商品【" + goods.getName() + "】数量不足！无法下单，剩余数量：" + goods.getBanlanceNumber());
			}
			BigDecimal price = goods.getPrice().multiply(new BigDecimal(request.getNumber().toString()));
			BigDecimal voucherPrice = goods.getVoucherPrice().multiply(new BigDecimal(request.getNumber().toString()));
			goodsTotalPrice = goodsTotalPrice.add(price).setScale(2, BigDecimal.ROUND_HALF_UP);
			goodsTotalVoucherPrice = goodsTotalVoucherPrice.add(voucherPrice).setScale(2, BigDecimal.ROUND_HALF_UP);

			// 减掉剩余数量 增加销售量
			ProjectGoodsPrice updateGoods = new ProjectGoodsPrice();
			updateGoods.setId(goods.getId());
			updateGoods.setBanlanceNumber(goods.getBanlanceNumber() - request.getNumber());
			if (projectGoodsPriceMapper.updateByPrimaryKeySelective(updateGoods) == 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "更改商品剩余数量出错");
			}

			UserReceivingAddress address = userReceivingAddressMapper.selectByPrimaryKey(request.getAddressId());
			if (address == null) {
				throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
			}

			// 生成主订单
			Date nowDate = new Date();
			OrderMain main = new OrderMain();
			main.setOrderNumber(PublicMethod.getOrderNumber(PublicConstant.ORDER_TYPE_1, null));
			main.setUserId(request.getUserId());
			main.setDistributorId(request.getDistributorId());
			main.setOrderStatus(OrderStatusEnum.MAIN_ORDER_STATUS_1.getStatus());
			main.setCreateTime(nowDate);
			main.setInvalidTime(DateUtils.getAddorSubtractTimes(nowDate, 0, PublicConstant.ORDER_INVALID_TIME, 0, 0, 0, 0));
			main.setActualPrice(goodsTotalPrice.add(logisticsPrice));
			main.setVoucherPrice(goodsTotalVoucherPrice);
			main.setLogisticsPrice(logisticsPrice);
			main.setTotalPrice(main.getActualPrice().add(main.getVoucherPrice()));
			main.setSource(request.getSource());
			main.setRemark(request.getRemark());
			main.setIp(PublicMethod.getIp(PublicMethod.getRequest()));
			if (orderMainMapper.insertSelective(main) == 0 || main.getId() == null) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "主订单," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}
			// 地址
			OrderAddress orderAddress = BeanMapper.map(address, OrderAddress.class);
			orderAddress.setMainOrderId(main.getId());
			orderAddress.setId(null);
			if (orderAddressMapper.insertSelective(orderAddress) == 0) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "记录地址失败," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}
			// 订单详情
			OrderDetail detail = new OrderDetail();
			detail.setMainOrderId(main.getId());
			detail.setNumber(request.getNumber());
			detail.setOriginalProjectId(goods.getId());
			if (orderDetailMapper.insertSelective(detail) == 0 || detail.getId() == null) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "详情," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}
			// 商品
			OrderGoods orderGoods = BeanMapper.map(goods, OrderGoods.class);
			orderGoods.setOrderDetailId(detail.getId());
			orderGoods.setCategoryId(goods.getCategory().getCategoryId());
			orderGoods.setId(null);
			if (orderGoodsMapper.insertSelective(orderGoods) == 0) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "商品创建失败," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}

			// 返回
			OrderCreateResponse response = new OrderCreateResponse();
			response.setOrderNumber(main.getOrderNumber());
			response.setOrderStatus(main.getOrderStatus());
			response.setCreateTime(main.getCreateTime());
			response.setInvalidTime(main.getInvalidTime());
			response.setActualPrice(main.getActualPrice());
			return response;
		}
	}

	@Override
	public OrderDetailResponse orderDetail(String orderNumber, Long userId, Long orderId) throws ProAffairException {
		OrderDetailResponse response = orderMainMapper.detailForApi(orderNumber, orderId);
		if (response == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		if (response.getUserId() != userId) {
			throw new ProRunTimeException(ErrCode.ORDER_NO_REQUEST.getReturnCode(), ErrCode.ORDER_NO_REQUEST.getReturnMsg());
		}
		int totalNumber = 0;
		for (OrderDetail o : response.getGoodsList()) {
			totalNumber += o.getNumber();
		}
		response.setTotalNumber(totalNumber);
		return response;
	}

	@Override
	@Transactional
	public Object pay(String orderNumber, Long userId, Integer payType, Integer source) throws ProAffairException {
		OrderDetailResponse response = orderMainMapper.detailForApi(orderNumber, null);
		if (response == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		if (response.getUserId() != userId) {
			throw new ProRunTimeException(ErrCode.ORDER_NO_REQUEST.getReturnCode(), ErrCode.ORDER_NO_REQUEST.getReturnMsg());
		}
		if (response.getOrderStatus() != OrderStatusEnum.MAIN_ORDER_STATUS_1.getStatus()) {
			throw new ProRunTimeException(ErrCode.ORDER_STATUS_UPDATE.getReturnCode(), ErrCode.ORDER_STATUS_UPDATE.getReturnMsg() + ":无法完成支付");
		}
		if (response.getInvalidTime().getTime() <= System.currentTimeMillis()) {
			throw new ProRunTimeException(ErrCode.ORDER_STATUS_UPDATE.getReturnCode(), "该订单已经过期，不能继续支付");
		}
		for (OrderDetail order : response.getGoodsList()) {
			ProjectGoods goods = projectGoodsMapper.detailApi(order.getOriginalProjectId(), userId);
			if (goods == null) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "商品已经下架！无法支付");
			}
			if (goods.getStatus() != PublicConstant.GOODS_STATUS_1) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "商品【" + goods.getName() + "】已经下架！无法支付");
			}
		}
		if (payType == null) {
			payType = 2;
		}
		SysPayment payment = paymentMapper.selectByPayTypeAndSource(payType, source);
		if (payment == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), "支付信息不存在");
		}
		response.setPayNumber(PublicMethod.getOrderNumber(PublicConstant.ORDER_TYPE_2, response.getId()));
		// 修改订单
		OrderMain orderMain = new OrderMain();
		orderMain.setId(response.getId());
		orderMain.setPayNumber(response.getPayNumber());
		orderMain.setPayBossAccount(payment.getPayBossAccount());

		if (orderMainMapper.updateByPrimaryKeySelective(orderMain) == 0) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), "记录 支付订单号失败");
		}
		// 小程序支付
		if (PayCodeEnum.WECHAT.getType() == payment.getPayType() && PayCodeEnum.SOURCE_1.getType() == source) {
			return WXPayUtils.xcxPay(response, payment, userLoginMapper.selectByUserIdAndAppid(response.getUserId(), payment.getPayAppid()));
		}
		// H5支付
		if (PayCodeEnum.WECHAT.getType() == payment.getPayType() && PayCodeEnum.SOURCE_2.getType() == source) {
			return WXPayUtils.h5Pay(response, payment);
		}
		// 微信公众号支付
		if (PayCodeEnum.WECHAT.getType() == payment.getPayType() && PayCodeEnum.SOURCE_3.getType() == source) {
			return WXPayUtils.publicNumberPay(response, payment, userLoginMapper.selectByUserIdAndAppid(response.getUserId(), payment.getPayAppid()));
		}
		// 微信APP支付
		if (PayCodeEnum.WECHAT.getType() == payment.getPayType() && (PayCodeEnum.SOURCE_4.getType() == source || PayCodeEnum.SOURCE_5.getType() == source)) {
			return WXPayUtils.appPay(response, payment);
		}
		// 阿里云支付
		if (PayCodeEnum.ALIPAY.getType() == payment.getPayType() && (PayCodeEnum.SOURCE_4.getType() == source || PayCodeEnum.SOURCE_5.getType() == source)) {
			String body = AlipayUtils.appPay(payment, response.getGoodsList().get(0).getName(), response.getPayNumber(), response.getActualPrice().toString(),
					response.getInvalidTime());
			if (StringUtils.isEmpty(body)) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "获取支付宝信息失败");
			}
			Map<String, String> map = new HashMap<String, String>();
			map.put("alipayAppBody", body);
			return map;
		}
		throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "没有该支付信息");
	}

	@Override
	@Transactional
	public void dealPayNotify(PayResultMsg payResultMsg) throws ProAffairException {
		// 根据支付订单号查询订单
		OrderSearchResponse order = orderMainMapper.selectByPayNumber(payResultMsg.getOrderNumber());
		if (order == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		// 微信设置Unionid
		if (PayCodeEnum.WECHAT.getType().intValue() == payResultMsg.getPayType().intValue()) {
			asyncMethod.settingUnionid(order.getUserId(), payResultMsg.getAppid(), payResultMsg.getOpenid(), payResultMsg.getBillNo());
		}
		if (payResultMsg.getPayPrice().doubleValue() != order.getActualPrice().doubleValue()) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "支付金额不对等,需人工排查订单");
		}
		if (OrderStatusEnum.MAIN_ORDER_STATUS_1.getStatus().intValue() != order.getOrderStatus().intValue()) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "该订单已经处理过了：" + order.getOrderStatus());
		}
		order.setPayType(payResultMsg.getPayType());
		order.setPayBillNumber(payResultMsg.getBillNo());
		order.setOrderStatus(OrderStatusEnum.MAIN_ORDER_STATUS_2.getStatus());
		order.setPayTime(payResultMsg.getPayTime());
		if (orderMainMapper.updateByPrimaryKeySelective(order) == 0) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "修改订单失败,需人工排查订单");
		}
		// 记录流水
		UserTransactionFlow flow = new UserTransactionFlow();
		flow.setUserId(order.getUserId());
		flow.setResType(PublicConstant.RES_TYPE_6);
		flow.setResId(order.getId());
		flow.setFlowType(PublicConstant.FLOW_TYPE_2);
		flow.setPrice(order.getActualPrice());
		flow.setReason("商品付款");
		if (userTransactionFlowMapper.insertSelective(flow) <= 0) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "记录流水失败");
		}

		try {
			// 发送系统消息
			MessageData record = new MessageData();
			record.setSendUserId(0L);
			record.setReceiveUserId(order.getDistributor().getAdminUserId());
			record.setType(PublicConstant.MESSAGE_TYPE_1);
			record.setTitle("订单提醒");
			record.setMessage("尊敬的商户您好，您产生了一笔支付订单，请及时查看订单配货，等待配送工作人员到达！订单号：" + order.getOrderNumber());
			messageDataMapper.insertSelective(record);
		} catch (Exception e) {
		}
	}

	@Override
	public void invalidOrderCancel() {
		List<OrderSearchResponse> invalidOrderList = orderMainMapper.selectForInvalidOrder();
		if (invalidOrderList == null || invalidOrderList.size() == 0) {
			return;
		}
		for (OrderSearchResponse o : invalidOrderList) {
			try {
				// 设置为取消订单
				OrderMain orderMain = new OrderMain();
				orderMain.setId(o.getId());
				orderMain.setOrderStatus(OrderStatusEnum.MAIN_ORDER_STATUS_5.getStatus());
				if (orderMainMapper.updateByPrimaryKeySelective(orderMain) == 0) {
					throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "修改订单状态失败");
				}

				// 返还库存
				for (OrderDetail d : o.getGoodsList()) {
					projectGoodsPriceMapper.updateBanlanceNumber(d.getOrderDetailId(), d.getNumber());
				}

			} catch (Exception e) {
				LOG.error("-订单-取消订单->{},异常:{}", o.getOrderNumber(), PublicMethod.printErrorTrace(e));
			}
		}
	}

	@Override
	public PageInfo<OrderSearchResponse> orderListForApi(PageBean<OrderSearchRequest> request) throws ProAffairException {
		PageHelper.startPage(request.getPageNum(), request.getPageSize());
		List<OrderSearchResponse> list = orderMainMapper.orderListForApi(request.getParam());
		if (list == null || list.size() == 0) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		for (OrderSearchResponse resp : list) {
			int totalNumber = 0;
			for (OrderDetail o : resp.getGoodsList()) {
				totalNumber += o.getNumber();
			}
			resp.setTotalNumber(totalNumber);
		}
		return new PageInfo<>(list);
	}

	@Override
	@Transactional
	public void updateOrderByIsdelete(List<Long> orderIds) throws ProAffairException {
		for (Long id : orderIds) {
			OrderMain orderMain = new OrderMain();
			orderMain.setId(id);
			orderMain.setIsDelete(0);
			if (orderMainMapper.updateByPrimaryKeySelective(orderMain) == 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "删除订单发生错误,请重试");
			}
		}
	}

	@Override
	@Transactional
	public void updateOrderByCancel(Long orderId, Long userId) throws ProAffairException {
		OrderMain orderMain = orderMainMapper.selectByPrimaryKey(orderId);
		if (orderMain == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		if (userId != orderMain.getUserId()) {
			throw new ProRunTimeException(ErrCode.ORDER_NO_REQUEST.getReturnCode(), ErrCode.ORDER_NO_REQUEST.getReturnMsg());
		}
		if (OrderStatusEnum.MAIN_ORDER_STATUS_1.getStatus() != orderMain.getOrderStatus()) {
			throw new ProRunTimeException(ErrCode.ORDER_STATUS_UPDATE.getReturnCode(), ErrCode.ORDER_STATUS_UPDATE.getReturnMsg());
		}
		orderMain.setOrderStatus(OrderStatusEnum.MAIN_ORDER_STATUS_5.getStatus());
		if (orderMainMapper.updateByPrimaryKeySelective(orderMain) == 0) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "取消订单发生错误,请重试");
		}
	}

	@Override
	@Transactional
	public void confirmReceivingGoods(Long orderId, Long userId) throws ProAffairException {
		OrderMain orderMain = orderMainMapper.selectByPrimaryKey(orderId);
		if (orderMain == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		if (userId != orderMain.getUserId()) {
			throw new ProRunTimeException(ErrCode.ORDER_NO_REQUEST.getReturnCode(), ErrCode.ORDER_NO_REQUEST.getReturnMsg());
		}
		if (OrderStatusEnum.MAIN_ORDER_STATUS_3.getStatus() != orderMain.getOrderStatus()) {
			throw new ProRunTimeException(ErrCode.ORDER_STATUS_UPDATE.getReturnCode(), "该订单目前不是已发货状态,无法确认收货");
		}
		orderMain.setOrderStatus(OrderStatusEnum.MAIN_ORDER_STATUS_4.getStatus());
		orderMain.setReceivingTime(new Date());
		if (orderMainMapper.updateByPrimaryKeySelective(orderMain) == 0) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "确认收货发生错误,请重试");
		}
	}

	@Override
	public List<OrderStatusNumberResponse> getOrderStatusNumber(Long userId) throws ProAffairException {
		List<OrderStatusNumberResponse> list = orderMainMapper.getOrderStatusNumberList(userId);
		if (list == null || list.size() == 0) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return list;
	}

	@Override
	@Transactional
	public OrderDetailResponse applyRefund(OrderApplyRefundRequest request) throws ProAffairException {
		if (StringUtils.isEmpty(request.getOrderNumber()) || request.getRefundPrice() == null) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
		}
		OrderDetailResponse detail = orderMainMapper.detailForApi(request.getOrderNumber(), null);
		if (detail == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		if (request.getUserId() != detail.getUserId()) {
			throw new ProRunTimeException(ErrCode.ORDER_NO_REQUEST.getReturnCode(), ErrCode.ORDER_NO_REQUEST.getReturnMsg());
		}
		if (OrderStatusEnum.MAIN_ORDER_STATUS_2.getStatus() != detail.getOrderStatus() && OrderStatusEnum.MAIN_ORDER_STATUS_3.getStatus() != detail.getOrderStatus()
				&& OrderStatusEnum.MAIN_ORDER_STATUS_4.getStatus() != detail.getOrderStatus()) {
			throw new ProRunTimeException(ErrCode.ORDER_STATUS_NO_REFUND.getReturnCode(), ErrCode.ORDER_STATUS_NO_REFUND.getReturnMsg());
		}
		if (detail.getActualPrice().doubleValue() < request.getRefundPrice().doubleValue()) {
			throw new ProRunTimeException(ErrCode.ORDER_STATUS_NO_REFUND.getReturnCode(), "退款金额大于购买价格");
		}
		if (detail.getRefund() == null) {// 第一次申请
			// 生成退款单
			OrderRefund refund = new OrderRefund();
			refund.setMainOrderId(detail.getId());
			refund.setRefundPrice(request.getRefundPrice());
			refund.setRefundNumber(PublicMethod.getOrderNumber(PublicConstant.ORDER_TYPE_3, detail.getId()));
			refund.setRefundStatus(OrderStatusEnum.REFUND_ORDER_STATUS_7.getStatus());
			refund.setRemark(request.getRemark());
			refund.setRefundImage(request.getRefundImage());
			if (orderRefundMapper.insertSelective(refund) <= 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "退货退款申请失败");
			}
		} else {// 重新申请
			OrderRefund refund = detail.getRefund();
			if (OrderStatusEnum.REFUND_ORDER_STATUS_10.getStatus() != refund.getRefundStatus()) {
				throw new ProRunTimeException(ErrCode.ORDER_STATUS_NO_REFUND.getReturnCode(), "您已经申请过退货退款");
			}
			refund.setRefundPrice(request.getRefundPrice());
			refund.setRefundStatus(OrderStatusEnum.REFUND_ORDER_STATUS_7.getStatus());
			refund.setFailRemark("");
			refund.setRefundImage(request.getRefundImage());
			refund.setRemark(request.getRemark());
			// 重新申请先删除原来的，然后在提交，把最新提交的放到最后面审核
			if (orderRefundMapper.deleteByPrimaryKey(refund.getId()) <= 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "删除旧的退货退款失败");
			}
			refund.setId(null);
			refund.setUpdateTime(new Date());
			if (orderRefundMapper.insertSelective(refund) <= 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "退货退款再次申请失败");
			}
		}
		return orderDetail(request.getOrderNumber(), request.getUserId(), null);
	}

	@Override
	@Transactional
	public void revokeRefund(OrderRevokeRefundRequest request) throws ProAffairException {
		if (StringUtils.isEmpty(request.getOrderNumber())) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
		}
		OrderDetailResponse detail = orderMainMapper.detailForApi(request.getOrderNumber(), null);
		if (detail == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		if (request.getUserId().longValue() != detail.getUserId()) {
			throw new ProRunTimeException(ErrCode.ORDER_NO_REQUEST.getReturnCode(), ErrCode.ORDER_NO_REQUEST.getReturnMsg());
		}
		if (detail.getRefund() == null) {
			throw new ProRunTimeException(ErrCode.ORDER_NO_REFUND_REQUEST.getReturnCode(), ErrCode.ORDER_NO_REFUND_REQUEST.getReturnMsg());
		}
		OrderRefund refund = detail.getRefund();
		if (OrderStatusEnum.REFUND_ORDER_STATUS_7.getStatus() != refund.getRefundStatus() && OrderStatusEnum.REFUND_ORDER_STATUS_9.getStatus() != refund.getRefundStatus()) {
			throw new ProRunTimeException(ErrCode.ORDER_REFUND_DEAL.getReturnCode(), ErrCode.ORDER_REFUND_DEAL.getReturnMsg());
		}
		if (orderRefundMapper.deleteByPrimaryKey(refund.getId()) <= 0) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "撤销退货申请失败,请稍后重试");
		}
	}

	@Override
	@Transactional
	public void orderCommentScore(List<CommentScoreRequest> request, Long userId) throws ProAffairException {
		for (CommentScoreRequest req : request) {
			if (req.getComment() != null) {
				OrderComment comment = req.getComment();
				if (comment.getMainOrderId() == null || comment.getProjectId() == null) {
					throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
				}
				if (!StringUtils.isEmpty(comment.getContent())) {
					try {
						tencentUtils.checkMsg(comment.getContent());
					} catch (ProException e) {
						throw new ProRunTimeException(e.getErrorCode(), e.getErrorMsg());
					}
				}
				comment.setUserId(userId);
				comment.setImage(qiniuUtils.uploadImageUrl(comment.getImage()));
				if (orderCommentMapper.insertSelective(comment) <= 0) {
					throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), ErrCode.FAIL.getReturnMsg());
				}
			}
			if (req.getScore() != null) {
				OrderScore score = req.getScore();
				if (score.getMainOrderId() == null || score.getProjectId() == null) {
					throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
				}
				score.setUserId(userId);
				if (orderScoreMapper.insertSelective(score) <= 0) {
					throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), ErrCode.FAIL.getReturnMsg());
				}
			}
		}
	}

	@Override
	public PageInfo<OrderMyCommentResponse> myComment(PageBean<OrderMyCommentRequest> request) throws ProAffairException {
		PageHelper.startPage(request.getPageNum(), request.getPageSize());
		List<OrderMyCommentResponse> list = orderCommentMapper.myComment(request.getParam());
		if (list == null || list.size() == 0) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return new PageInfo<>(list);
	}

	@Override
	public OrderRefund getRefund(Long mainOrderId) throws ProAffairException {
		// OrderRefund refund = orderRefundMapper.selectByMainId(mainOrderId);
		// 待审核
		// 已审核
		// 已寄回
		// 退款中
		// 已完成
		if (orderRefundMapper.selectByMainId(mainOrderId) == null) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), ErrCode.FAIL.getReturnMsg());
		}
		return orderRefundMapper.selectByMainId(mainOrderId);
	}

}
